<?php

namespace App\Http\Controllers\Recommend;

use App\Http\Controllers\Controller;
use App\Http\Requests\Recommend\ApppageRectplDataRequest;
use App\Models\Application\Apppage;
use App\Models\Application\Muticolumn;
use App\Models\Application\Pagetpl;
use App\Models\Application\Paneltpl;
use App\Models\Entity\Asset\Video\Vasseti;
use App\Models\Entity\Column\Collist;
use App\Models\Entity\Column\ColumnType;
use App\Models\Entity\Column\Data;
use App\Models\Entity\Tag\tag;
use App\Models\Recommend\ApppageRectpl;
use App\Models\Recommend\ApppageRectplArea;
use App\Models\Recommend\ApppageRectplData;
use App\Models\Recommend\Reclist0;
use App\Repositories\Recommend\ApppageRectplDataRepository;
use DB;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Flash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Storage;
use Response;
use Validator;

class ApppageRectplDataController extends Controller
{
    use ModelForm;

    /** @var  ApppageRectplDataRepository */
    private $apppageRectplDataRepository;

    public function __construct(ApppageRectplDataRepository $apppageRectplDataRepo)
    {
        $this->apppageRectplDataRepository = $apppageRectplDataRepo;
    }

    /**
     * Display a listing of the ApppageRectplData.
     *
     * @return Response
     */
    public function index(Request $request)
    {
        return Admin::content(function (Content $content) use ($request) {

            $content->header(__('recommend.apppage_rectpl_datas.index_header'));
            $content->description(__('recommend.apppage_rectpl_datas.index_description'));

            $content->body($this->grid($request));
        });
    }

    /**
     * Show the form for creating a new ApppageRectplData.
     *
     * @return Response
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('recommend.apppage_rectpl_datas.create_header'));
            $content->description(__('recommend.apppage_rectpl_datas.create_description'));

            $content->body($this->form());

        });
    }

    /**
     * Store a newly created ApppageRectplData in storage.
     *
     * @param ApppageRectplDataRequest $request
     *
     * @return Response
     */
    public function store(ApppageRectplDataRequest $request)
    {
        $input = $request->all();

        // 单个页面只能对应单个布局
        $image = $request->file('img'); //使用laravel 自带的request类来获取一下文件.
        if ($image) {
            if ($image->isValid()) {
                // 允许上传的图片格式
                $allowed_extensions = ["png", "jpg", "gif", "jpeg"];
                if ($image->getClientOriginalExtension() && !in_array($image->getClientOriginalExtension(), $allowed_extensions)) {
                    return ['error' => 'You may only upload png, jpg, jpeg or gif.'];
                }
                $realPath = $image->getRealPath(); //临时文件的绝对路径
                // 获得图片的扩展名
                $extension = $image->getClientOriginalExtension();
                // 获取上传图片的文件名
                // $imagesName = $image->getClientOriginalName();
                // 重新命名上传文件名字
                $newImageName = md5(time()) . random_int(5, 5) . "." . $extension;
                // 上传图片
                $uploadConfig = config('custom.base.upload.apppage_rectpl_data');
                $driver       = $uploadConfig['driver'];
                $dir          = $uploadConfig['dir'];
                $rootDir      = config('filesystems.disks.' . $driver . '.upload');
                // 图片的完整路径
                $fullPath = $rootDir . '/' . $dir . '/' . $newImageName;

                $input['img'] = $fullPath;

                $bool = Storage::disk($driver)->put($fullPath, file_get_contents($realPath));
            }
        }

        // 如果添加的栏目列表,把插入模式缺省设置为list0
        if (!empty($input['data_id']) && !empty($input['insert_mode'])) {
            $columnTypeName = ColumnType::where(['id' => $input['data_id']])->value('name');
            if (in_array($columnTypeName, ['collist','reclist0'])) {
                $input['insert_mode'] = 2;
            }
        }

        $apppageRectplData = $this->apppageRectplDataRepository->create($input);
        if ($apppageRectplData) {
            // 保存当前栏目列表的标签
            if (is_array($request->get('tags'))) {
                $apppageRectplData->tags()->attach(array_filter($request->get('tags')));
            }
        }
        Flash::success(__('recommend.apppage_rectpl_datas.saved_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('recommend.apppage_rectpl_datas.index'));

    }

    /**
     * Display the specified ApppageRectplData.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $apppageRectplData = $this->apppageRectplDataRepository->findWithoutFail($id);

        if (empty($apppageRectplData)) {
            Flash::error(__('recommend.apppage_rectpl_datas.not_found'));

            return redirect(route('recommend.apppage_rectpl_datas.index'));
        }

        return view('recommend.apppage_rectpl_datas.show')->with('apppageRectplData', $apppageRectplData);

    }

    /**
     * Show the form for editing the specified ApppageRectplData.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {
        $apppageRectplData = $this->apppageRectplDataRepository->findWithoutFail($id);

        if (empty($apppageRectplData)) {
            Flash::error(__('recommend.apppage_rectpl_datas.not_found'));

            return redirect(route('recommend.apppage_rectpl_datas.index'));
        }
        return Admin::content(function (Content $content) use ($id, $apppageRectplData) {

            $content->header(__('recommend.apppage_rectpl_datas.edit_header'));
            $content->description(__('recommend.apppage_rectpl_datas.edit_description'));

            $content->body($this->form()->edit($id));
            $range = $apppageRectplData->range ? $apppageRectplData->range : 0;
            $content->row(view('recommend.apppage-rectpl-datas.edit', ['data_id' => $apppageRectplData->data_id, 'resource_data_id' => $apppageRectplData->resource_data_id, 'range' => $range, 'tpl_id' => $apppageRectplData->tpl_id]));

        });
    }

    /**
     * Update the specified ApppageRectplData in storage.
     *
     * @param  int              $id
     * @param ApppageRectplDataRequest $request
     *
     * @return Response
     */
    public function update($id, Request $request)
    {
        $apppageRectplData = $this->apppageRectplDataRepository->findWithoutFail($id);

        if (empty($apppageRectplData)) {
            Flash::error(__('recommend.apppage_rectpl_datas.not_found'));

            return redirect(route('recommend.apppage_rectpl_datas.index'));
        }
        $input = $request->all();
        if (array_key_exists('_file_del_', $input)) {
            $imgUrl       = $apppageRectplData->img;
            $uploadConfig = config('custom.base.upload.apppage_rectpl_data');
            $driver       = $uploadConfig['driver'];
            $dir          = $uploadConfig['dir'];
            $rootDir      = config('filesystems.disks.' . $driver . '.upload');
            if ($flag = Storage::disk($driver)->delete($imgUrl)) {
                $apppageRectplData->img = null;
                $apppageRectplData->img->save();
            }
            return response()->json(['message' => '删除成功', 'status' => true]);
        }

        $sValidators = [
            'area'             => 'required|max:100',
            'data_id'          => 'required',
            'resource_data_id' => 'required',
            // 添加方式
            // 'insert_mode'      => 'required',
        ];

        $validators = [];

        // 动态判断校验
        foreach ($input as $key => $value) {
            if (isset($sValidators[$key])) {
                $validators[$key] = $sValidators[$key];
            }
        }

        // 定义校验, 没有移到request
        $validator = Validator::make($request->all(), $validators, [
            'required' => ':attribute 不能为空',
        ], [
            'area'             => '区位编号',
            'data_id'          => '数据类型',
            'resource_data_id' => '数据ID',
            // 'insert_mode'      => '添加方式',
        ]);

        if ($validator) {
            // 校验
            if ($validator->fails()) {
                return back()->withErrors($validator)->withInput();
            }
        }

        $image = $request->file('img'); //使用laravel 自带的request类来获取一下文件.
        if ($image) {
            if ($image->isValid()) {
                // 允许上传的图片格式
                $allowed_extensions = ["png", "jpg", "gif", "jpeg"];
                if ($image->getClientOriginalExtension() && !in_array($image->getClientOriginalExtension(), $allowed_extensions)) {
                    return ['error' => 'You may only upload png, jpg, jpeg or gif.'];
                }
                $realPath = $image->getRealPath(); //临时文件的绝对路径
                // 获得图片的扩展名
                $extension = $image->getClientOriginalExtension();
                // 获取上传图片的文件名
                // $imagesName = $image->getClientOriginalName();
                // 重新命名上传文件名字
                $newImageName = md5(time()) . random_int(5, 5) . "." . $extension;
                // 上传图片
                $uploadConfig = config('custom.base.upload.apppage_rectpl_data');
                $driver       = $uploadConfig['driver'];
                $dir          = $uploadConfig['dir'];
                $rootDir      = config('filesystems.disks.' . $driver . '.upload');
                // 图片的完整路径
                $fullPath = $rootDir . '/' . $dir . '/' . $newImageName;

                $input['img'] = $fullPath;
                $flag         = Storage::disk($driver)->delete($apppageRectplData->img);

                $bool = Storage::disk($driver)->put($fullPath, file_get_contents($realPath));
            }
        }
        // 如果添加的栏目列表,把插入模式缺省设置为list0
        if (!empty($input['data_id']) && !empty($input['insert_mode'])) {
            $columnTypeName = ColumnType::where(['id' => $input['data_id']])->value('name');
            if (in_array($columnTypeName, ['collist','reclist0'])) {
                $input['insert_mode'] = 2;
            }
        }
        $apppageRectplData = $this->apppageRectplDataRepository->update($input, $id);
        if ($apppageRectplData) {
            // 保存当前栏目列表的标签
            if (is_array($request->get('tags'))) {
                // $collist->tags()->detach();
                $apppageRectplData->tags()->sync(array_filter($request->get('tags')));
            }
        }
        Flash::success(__('recommend.apppage_rectpl_datas.updated_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('recommend.apppage_rectpl_datas.index'));
    }

    /**
     * Remove the specified ApppageRectplData from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        // 根据 `,` 判断传递过来的是单个id还是多个id
        if (substr_count($id, ',') >= 1) {
            $id = explode(",", $id);
        }

        // 如果是数组则进行批量删除
        if (is_array($id)) {
            if ($flag = $this->apppageRectplDataRepository->batchDelete('id', $id)) {

                return response()->json(['message' => __('recommend.apppage_rectpl_datas.deleted_success'), 'status' => $flag]);
            } else {
                return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
            }
        }

        $apppageRectplData = $this->apppageRectplDataRepository->findWithoutFail($id);

        if (empty($apppageRectplData)) {
            Flash::error(__('recommend.apppage_rectpl_datas.not_found'));

            return redirect(route('recommend.apppage_rectpl_datas.index'));
        }

        if ($flag = $this->apppageRectplDataRepository->delete($id)) {
            // 取消与标签的关联
            $apppageRectplData->tags()->detach();

            return response()->json(['message' => __('recommend.apppage_rectpl_datas.deleted_success'), 'status' => $flag]);
        } else {
            return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
        }
    }

    /**
     * [form description]
     * @return {[type]} [description]
     */
    protected function form()
    {
        return Admin::form(ApppageRectplData::class, function (Form $form) {

            $form->display('id', 'ID');
            // $form->text('name', '推荐数据名称');
            $form->text('title', '推荐标题');
            $form->text('subtitle', '推荐副标题');
            // $pagetpls = Pagetpl::pluck('title', 'id');
            //    $form->select('pagetpl_id', '页面模板')->options($pagetpls);
            $form->hidden('apppage_rectpl_area_id', '推荐模板区位ID');
            $form->hidden('pagetpl_id', '页面模板');
            $paneltpls = Paneltpl::pluck('title', 'id');
            $form->select('paneltpl_id', '模板编号')->options($paneltpls);
            $form->text('area', '区位编号')->help('range为area时填写');

            // 添加方式
            // insert_mode
            $form->select('insert_mode', '添加方式')->options(array(
                '1' => 'meta模式',
                '2' => 'list0模式',
            ))->default(1);
            $tmpColumnTypes = ColumnType::get(['tags', 'id', 'title', 'pid'])->toArray();
            $tempArr        = [];
            foreach ($tmpColumnTypes as $key => $columnType) {
                $tags = explode(',', $columnType['tags']);
                foreach ($tags as $tag) {
                    if (in_array(trim($tag), ['any', 'page_rectpl'])) {
                        $tempArr[] = $columnType['id'];
                    }
                }
            }
            $columnTypes = ColumnType::whereIn('id', $tempArr)->get(['id', 'pid', 'title'])->toArray();
            $columnTypes = array_merge([['id' => 0, 'pid' => 0, 'title' => '选择']], $columnTypes);
            $form->ztree('data_id', '数据类型')
                ->zTreeConfig(["map" => ["id" => "id", "title" => 'name', 'pid' => 'pId'], "type" => "radio", "open" => true])
                ->options($columnTypes)->default('1')->load('resource_data_id', route('application.collist_datas.datas.resources'), 'id', 'title');
            $muticolumns = Muticolumn::orderBy('listorder', 'asc')->pluck('title', 'id');
            $form->select('resource_data_id', '数据ID')->options($muticolumns);
            $form->select('range', 'range')->options(array(
                '0' => '选择',
                '1' => 'area',
                '2' => 'page',
                '3' => 'app',
                '4' => 'list',
            ))->load('tpl_id', route('entity.column.collists.tpls'), 'id', 'title')->help('选中range时模板不能为空');

            $paneltpls = Paneltpl::pluck('title', 'id')->toArray();
            $form->select('tpl_id', '模板')->options(array_merge([0 => '选择'], $paneltpls));
            $form->text('position', 'area');
            // 用来区分栏目列表页面还是夜间
            $form->text('page_mode', 'data');

            $tags = tag::pluck('name', 'id');

            $form->multipleSelect('tags', '标签')->options($tags);
            $form->image('img', '推荐图')->removable();
            $form->number('order', '排序');
            $form->display('created_at', __('base.created_at'));
            $form->display('updated_at', __('base.updated_at'));

        });
    }

    /**
     * [grid description]
     * @return {[type]} [description]
     */
    protected function grid(Request $request)
    {

        return Admin::grid(ApppageRectplData::class, function (Grid $grid) use ($request) {
            // 考虑是否需要scope和排序
            $grid->model()->orderBy('order', 'desc');

            // 添加按钮
            // if (Admin::user()->cannot('recommend.apppage_rectpl_datas.create')) {
            $grid->disableCreation();
            // }

            // 编辑和删除按钮
            $grid->actions(function ($actions) {
                // 编辑按钮
                if (Admin::user()->cannot('recommend.apppage_rectpl_datas.edit')) {
                    $actions->disableEdit();
                }
                // 删除按钮
                if (Admin::user()->cannot('recommend.apppage_rectpl_datas.destroy')) {
                    $actions->disableDelete();
                }

            });

            // 导出按钮
            if (Admin::user()->cannot('recommend.apppage_rectpl_datas.export')) {
                $grid->disableExport();
            }

            // 批量操作
            $grid->tools(function ($tools) {
                $tools->append('<a href="javascript:void(0)" onclick="history.go(-1)" class="btn btn-default btn-sm" style="margin-right: 0px"> <i class="fa fa-arrow-left"></i>返回</a>');
                $tools->batch(function ($batch) {
                    // 批量删除按钮
                    if (Admin::user()->cannot('recommend.apppage_rectpl_datas.batch_destroy')) {
                        $batch->disableDelete();
                    }
                });
            });

            $grid->column('id', 'ID')->sortable();
            // $grid->column('name', '推荐数据名称')->sortable();
            $grid->column('title', '推荐标题')->sortable();
            $grid->column('subtitle', '推荐副标题')->sortable();
            // $grid->column('pagetpl.title', '页面模板')->sortable();
            $grid->column('paneltpl.title', '模板编号')->sortable();
            $grid->column('area', '区位编号')->sortable();
            $grid->column('insert_mode', '添加方式')->display(function ($val) {
                switch ($val) {
                    case '1':
                        return '<span class="badge bg-green">meta模式</span>';
                        break;
                    case '2':
                        return '<span class="badge bg-green">list0模式</span>';
                        break;
                    default:
                        return '';
                }
            });
            $grid->column('columnType.title', '数据类型')->sortable();
            $grid->column('resource_data_id', '数据ID')->display(function ($value) {
                $name       = '';
                $columnType = ColumnType::where(['id' => $this->data_id])->first();
                if ($columnType) {
                    switch ($columnType->name) {
                        case 'collist':
                            $name = Collist::where(['id' => $this->resource_data_id])->value('title');
                            break;
                        case 'panellist':
                            $name = ApppageRectpl::where(['id' => $this->resource_data_id])->value('title');
                            break;
                        case 'reclist0':
                            $name = Reclist0::where(['id' => $this->resource_data_id])->value('title');
                            break;
                        case 'vodpkg':
                            $name = Vasseti::where(['id' => $this->resource_data_id])->value('title');
                            break;
                        case 'livepkg':
                            $name = Vasseti::where(['id' => $this->resource_data_id])->value('title');
                            break;
                        case 'assetpkg':
                            $name = Vasseti::where(['id' => $this->resource_data_id])->value('title');
                            break;
                        case 'column':
                            $name = Muticolumn::where(['id' => $this->resource_data_id])->value('title');
                            break;
                        case 'SPFJ':
                            $name = Vasseti::where(['id' => $this->resource_data_id])->value('title');
                            break;
                        case 'SPDJ':
                            $name = Vasseti::where(['id' => $this->resource_data_id])->value('title');
                            break;
                        default:
                            # code...
                            break;
                    }
                }
                return empty($name) ? '' : $name;
            });
            $grid->column('range', 'range')->display(function ($val) {
                switch ($val) {
                    case '1':
                        return '<span class="badge bg-green">area</span>';
                        break;
                    case '2':
                        return '<span class="badge bg-green">page</span>';
                        break;
                    case '3':
                        return '<span class="badge bg-green">app</span>';
                        break;
                    case '4':
                        return '<span class="badge bg-green">list</span>';
                        break;
                    default:
                        return '';
                        break;
                }
            });
            $grid->column('tpl_id', '模板')->display(function ($val) {
                $returnName = '';
                switch ($this->range) {
                    case '1':
                        $returnName = Paneltpl::where(['id' => $val])->value('title');
                        break;
                    default:
                        $returnName = Pagetpl::where(['id' => $val])->value('title');
                        break;
                }
                return empty($returnName) ? '' : $returnName;
            });
            $grid->column('position', 'area')->sortable();
            $grid->tags('标签')->pluck('name')->label();
            $grid->column('page_mode', 'data');
            // $grid->column('tags', '推荐标签')->sortable();
            $uploadConfig = config('custom.base.upload.apppage_rectpl_data');
            $driver       = $uploadConfig['driver'];
            $dir          = $uploadConfig['dir'];
            $uploadHosts  = config('custom.base.host');
            $host         = $uploadHosts[$driver];
            $grid->column('img', '推荐图')->image($host);
            $grid->column('order', '排序')->sortable();

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // // 禁用id查询框
                // $filter->disableIdFilter();
                $filter->like('name', '名称');
                // 推荐位
                $appageRectplAreas = ApppageRectplArea::pluck('area', 'id');
                $filter->equal('apppage_rectpl_area_id', '推荐区位')->select($appageRectplAreas);
                // 页面
                $tmpPagetpls = Paneltpl::pluck('title', 'id');
                $filter->equal('paneltpl_id', '页面')->select($tmpPagetpls);
                // 页面推荐位
                $tmpPaneltpls = Paneltpl::pluck('title', 'id');
                $filter->equal('paneltpl_id', '模板编号')->select($tmpPaneltpls);
                $filter->like('area', '名称');

            });
        });
    }
}
